package com.example.librarymanagementproject2.service.impl;


import com.example.librarymanagementproject2.Common.exception.GlobalException;
import com.example.librarymanagementproject2.mapper.EmailMapper;
import com.example.librarymanagementproject2.model.entity.EmailSendRecord;
import com.example.librarymanagementproject2.service.EmailService;
import com.example.librarymanagementproject2.service.enums.EmailEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName EmailServiceImpl
 * @Description TODO
 * @Author Kx
 * @Date 2025/10/16 20:27
 * @Version 1.0
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private EmailMapper emailMapper;

    @Autowired
    public RedisTemplate<String, Object> redisTemplate;

    /**
     * 邮箱发送工具对象
    */
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * @author: kx
     * @date: 2025/10/20 19:16
     * @return int
     * @description: 随机生成六位数验证码
    */
    private int generate6DigitCode() {
        Random random = new Random();
        // 生成100000-999999的随机数
        return random.nextInt(900000) + 100000;
    }

    /**
     * @author: kx
     * @date: 2025/10/20 19:39
     * @param recipientEmail : 接收用户邮箱
     * @param captcha : 验证码
     * @description: 存储验证码到Redis
    */
    private void storeCaptchaInRedis(String recipientEmail, int captcha) {
        redisTemplate.opsForValue().set(EmailEnum.CAPTCHA_PREFIX.value() + recipientEmail, captcha, 5, TimeUnit.MINUTES);
    }

    /**
     * @param recipientEmail : 接收用户邮箱
     * @author: kx
     * @date: 2025/10/20 19:19
     * @description: 发送验证码邮件
     */
    @Override
    public void insertEmailSendRecord(String recipientEmail) {
        if (recipientEmail == null) {
            throw new GlobalException(500, "接收用户邮箱不能为空");
        }
        // 生成6位数验证码
        int captcha = generate6DigitCode();
        try {
            // 构建一封简单的文本邮件
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            // 发件人邮箱（必须和配置中的 username 一致）
            mailMessage.setFrom("2195170852@qq.com");
            // 收件人，即刚刚注册的邮箱
            mailMessage.setTo(recipientEmail);
            // 邮箱标题
            mailMessage.setSubject("验证码");
            // 邮箱内容
            mailMessage.setText("欢迎注册 借书平台 服务，您的注册验证码：" + captcha + "。请在 5 分钟内完成填写，若未申请注册，请联系客服处理");
            // 发送邮件
            javaMailSender.send(mailMessage);
            try {
                // 存储验证码
                storeCaptchaInRedis(recipientEmail, captcha);
                // 设置邮件发送对象
                EmailSendRecord emailSendRecord = new EmailSendRecord();
                // 设置发送用户邮箱
                emailSendRecord.setSendEmail(mailMessage.getFrom());
                // 设置接收用户邮箱
                emailSendRecord.setRecipientEmail(recipientEmail);
                // 设置邮件标题
                emailSendRecord.setTitle(mailMessage.getSubject());
                // 设置邮件内容
                emailSendRecord.setContent(mailMessage.getText());
                // 插入邮件发送记录
                emailMapper.insertEmailSendRecord(emailSendRecord);
            } catch (Exception e) {
                throw new GlobalException(500, "邮件发送成功，验证码存储或记录插入失败" + e.getMessage());
            }
        } catch (Exception e) {
            throw new GlobalException(500, "邮件发送失败" + e.getMessage());
        }
    }

    /**
     * @author: kx
     * @date: 2025/10/28 11:08
     * @param recipientEmail : 接收用户邮箱
     * @param bookName : 图书名称
     * @param borrowId : 借阅图书记录ID
     * @description: 发送图书借阅验证码
    */
    @Override
    public void sendBookBorrowCode(String bookName, String recipientEmail, Long borrowId) {
        if (recipientEmail == null) {
            throw new GlobalException(500, "接收用户邮箱不能为空");
        }
        // 生成6位数验证码
        int captcha = generate6DigitCode();
        try {
            // 构建一封简单的文本邮件
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            // 发件人邮箱（必须和配置中的 username 一致）
            mailMessage.setFrom("2195170852@qq.com");
            // 收件人，即刚刚注册的邮箱
            mailMessage.setTo(recipientEmail);
            // 邮箱标题
            mailMessage.setSubject("借阅图书验证码");
            // 邮箱内容
            mailMessage.setText("您正在申请借阅《" + bookName + "》，本次操作验证码：" + captcha + "。\n" +
                    "请在5分钟内输入验证码完成借阅确认，超时将自动失效。\n" +
                    "若不是您本人操作，请及时登录平台查看借阅记录或联系客服。");
            // 发送邮件
            javaMailSender.send(mailMessage);
            try {
                // 存储验证码
                Map<String, Object> verifyInfo = new HashMap<>();
                verifyInfo.put("code", captcha);       // 系统生成的验证码原文
                verifyInfo.put("borrowId", borrowId); // 关联的借阅记录ID
                redisTemplate.opsForValue().set(EmailEnum.CAPTCHA_PREFIX.value() + recipientEmail, verifyInfo, 5, TimeUnit.MINUTES);
                // 设置邮件发送对象
                EmailSendRecord emailSendRecord = new EmailSendRecord();
                // 设置发送用户邮箱
                emailSendRecord.setSendEmail(mailMessage.getFrom());
                // 设置接收用户邮箱
                emailSendRecord.setRecipientEmail(recipientEmail);
                // 设置邮件标题
                emailSendRecord.setTitle(mailMessage.getSubject());
                // 设置邮件内容
                emailSendRecord.setContent(mailMessage.getText());
                // 插入邮件发送记录
                emailMapper.insertEmailSendRecord(emailSendRecord);
            } catch (Exception e) {
                throw new GlobalException(500, "邮件发送成功，验证码存储或记录插入失败" + e.getMessage());
            }
        } catch (Exception e) {
            throw new GlobalException(500, "邮件发送失败" + e.getMessage());
        }
    }
}
